﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RedesII_DTL;
using System.Data.Common;

namespace RedesII_DAL
{
    public class ServiceDao
    {
        public ServiceDto GetByProcess(string process)
        {
            string query = "SELECT ID_SERVICO, SERVICO FROM WMI_SERVICOS WHERE SERVICO = '" + process.ToString() + "'";
            var service = BuscaRegistro(query);
            if (service != null)
            {
                return service;
            }
            else
                return null;
        }

        public bool InsertService(ServiceDto service)
        {
            string query =
                String.Format("INSERT INTO WMI_SERVICOS (SERVICO) VALUES ('{0}')",
                service._Servico);
            return ExecutaComando(query);
        }


        protected ServiceDto BuscaRegistro(string query)
        {
            // criando a conexão com o banco
            DaoFactory factory = new DaoFactory();
            DbConnection connection = factory.CriaConexao();
            // criando o comando que vai ser executado
            DbCommand cmd = factory.CriaComando();
            cmd.Connection = connection;
            cmd.CommandText = query;
            // abrindo a conexão
            connection.Open();
            // executando o comando e obtendo um reader (leitor de dados)
            DbDataReader reader = cmd.ExecuteReader();
            // criando um usuario
            ServiceDto service = new ServiceDto();
            // para cada registro lido pelo reader
            while (reader.Read())
            {
                service._IdServico = (int)reader["ID_SERVICO"];
                service._Servico = (string)reader["SERVICO"];
            }
            // fechando a conexão
            connection.Close();
            return service;
        }

        protected virtual bool ExecutaComando(string query)
        {
            DaoFactory factory = new DaoFactory();
            // criando a conexão com o banco
            DbConnection connection = factory.CriaConexao();
            // criando o comando que vai ser executado
            DbCommand cmd = factory.CriaComando();
            cmd.Connection = connection;
            cmd.CommandText = query;
            // abrindo a conexão
            connection.Open();
            // executando o comando e obtendo um reader (leitor de dados)
            int res = cmd.ExecuteNonQuery();
            // fechando a conexão
            connection.Close();
            return res > 0;
        }
    }
}
